package cmbchina.util.http;

import cmbchina.util.AjaxJson;
import cmbchina.util.JacksonUitl;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by sevenlm on 2018/1/4.
 */
public class Test{

    private static final Logger LOGGER = LoggerFactory.getLogger(Test.class);
    private static  String dashboard_url= "192.168.1.2";
    private static String dashboard_usernmae =  "sjkjkpt";
    private static String dashboard_passWorld = "sjkjkpt@123456";
    private static int dashboard_port = 80;
    private static String dashboard_protocol = "http";
    private static String dashboard_apiurl = "/W/flowable-task/app/rest/createProcessInstanceBykey";

    /**
     * rest post 方式调用itil接口
     * @param JsonParams json格式的请求参数
     * @return
     * @throws Exception
     */
    public  AjaxJson httpRequestPost(String JsonParams,String dashboard_apiurl){

        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.setSuccess(false);
        ajaxJson.setMsg("LINUX");
        try{

            HttpHost targetHost = new HttpHost(dashboard_url, dashboard_port, dashboard_protocol);

            DefaultHttpClient httpclient = new DefaultHttpClient();
       /* 请求超时*/
            httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000*60*60);
        /*读取超时*/
            httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000*60*60);

            //此用户名和密码上生产前需要修改为自己的账户
            httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                    new UsernamePasswordCredentials(dashboard_usernmae, dashboard_passWorld));

            AuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(targetHost, basicAuth);

            BasicHttpContext localcontext = new BasicHttpContext();
            localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
            String url = dashboard_protocol+"://"+dashboard_url+":"+dashboard_port+dashboard_apiurl;

            HttpPost httpPost = new  HttpPost(url);

            StringEntity stringEntity = new StringEntity(JsonParams, HTTP.UTF_8);

            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            httpPost.setHeader("accept","application/json");

            httpPost.setEntity(stringEntity);

            HttpResponse response = httpclient.execute(targetHost, httpPost, localcontext);

            HttpEntity entity = response.getEntity();

            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println(dashboard_apiurl+" ====================StatusCode:" + statusCode);
            Map<String,Object> mapResult = new HashMap<String,Object>();

            if(statusCode == 200) {

                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(),"utf-8"));
                String buffer  = "";
                StringBuffer sb = new StringBuffer();
                while((buffer = reader.readLine())!=null){
                    sb.append(buffer);
                }
                reader.close();
                httpPost.releaseConnection();
                System.out.println("entity:" + sb.toString());
                httpclient.getConnectionManager().shutdown();


                ajaxJson = JacksonUitl.getObjectMapper().readValue(sb.toString(), AjaxJson.class);

            }else{
                ajaxJson.setCode(statusCode+"");
                ajaxJson.setMsg(statusCode+"");


            }

        }catch (Exception e){
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setCode("400");
            LOGGER.error("",e);
        }

        return ajaxJson;
    }

    public AjaxJson CheckScriptNameRequest(String requestParams){

        String apiUrl = "/api/rest/queryScriptType";
        return this.httpRequestPost(requestParams,apiUrl);
    }

    public AjaxJson sendSms(String requestParams){

        String apiUrl = "/api/rest/sendMsm";
        return this.httpRequestPost(requestParams,apiUrl);
    }

    public AjaxJson checkItilNum(String requestParams){
        String apiUrl = "/api/rest/checkItilNumber";
        return this.httpRequestPost(requestParams,apiUrl);
    }



    public static void main(String[] args) throws Exception {

        String rs = "!!appadm_high9L!!ck1XO!!";
        String rsTrim = rs.trim();
        if(rsTrim.indexOf("!!")==0){
            rsTrim = rsTrim.substring(2,rsTrim.length()-2);
            String [] rsArray = rsTrim.split(":");
            System.out.println(rsArray.length);
//            System.out.println(rsArray[1]);
        }
        String pp = "{        \"deploymentKey\": \"dbLogChangeApp\",        \"name\": \"DB2活动日志空间临时调整test\",        \"processDefinitionKey:\" \"dbLogChangeFlow\",        \"source\": \"数据库监控管理平台\",        \"userId\": \"admin\",        \"userName\": \"admin\",        \"values\": {            \"dbname\": \"ABIMSDB1\",            \"hostname\": \"devenvdb2\",            \"instname\": \"hxinst1\"        }    } ";
//        Map<String,Object> mapResult = DbServiceRequestUtil.httpRequestPost(pp);
        System.out.println("Hello World");
        String sb = "{\"success\":\"true\", \"msg\":\"test\"}";
//        AjaxJson ajaxJson=new Test().httpRequestPost(pp,"/W/flowable-task/app/rest/cusProcessInstanceByKey");//JacksonUitl.getObjectMapper().readValue(pp.toString(), AjaxJson.class);

        int i = 0;
    }
}
